package com.tanguy.user.ui.me.activity.account

import android.app.Activity
import android.view.View
import com.tanguy.user.App.Companion.app
import com.tanguy.user.Const
import com.tanguy.user.R
import com.tanguy.user.base.ImmersionTitleActivity
import com.tanguy.user.net.http.HttpManager
import com.tanguy.user.utlis.extend.*
import kotlinx.android.synthetic.main.activity_set_password.*

/**
 * 设置密码
 * type:
 * 0:设置密码(默认)
 * 1.验证手机,并设置密码,没有跳过
 * 2.修改密码
 */
class SetPasswordActivity : ImmersionTitleActivity() {
    override fun setContentViewRes(): Int = R.layout.activity_set_password
    var type = 0
    override fun initView() {
        super.initView()
        type = intent.getIntExtra("type", 0)
        when (type) {
            0 -> setPassword()
            1 -> setPasswordAndLogin()
            2 -> changePassword()
        }
    }


    //type=0
    private fun setPassword() {
        title = "设置密码"
        btn_next.text = "确认设置"
        titleBar.addRightButton("跳过", 0, View.OnClickListener {
            finish()
        }).setTextColor(getColorKt(R.color.color_ffffff))
        titleBar.showLeft(false)
        click(btn_next) {
            request {
                setResult(Activity.RESULT_OK)
                finish()
            }
        }
    }

    //type=1
    private fun setPasswordAndLogin() {
        title = "设置密码"
        btn_next.text = "确认设置并登录"
        val phone = intent.getStringExtra(Const.IntentCode.PHONE)
        if (!checkPhoneNumber(phone)) return
        click(btn_next) {
            request {
                HttpManager.paswLogin(phone, it)
                        .requestSucceed(this@SetPasswordActivity) {
                            checkLogin(it) {
                                if (it != null) {
                                    showToast(it)
                                    return@checkLogin
                                }
                                setResult(Activity.RESULT_OK)
                                finish()
                            }
                        }
            }
        }

    }

    //type=2
    private fun changePassword() {
        title = "修改密码"
        tv_hint.text = ""
        tv_one_password.text = "新密码\u3000\u3000"
        tv_two_password.text = "确认密码\u3000"
        click(btn_next) {
            request {
                showToast("密码修改成功")
                setResult(Activity.RESULT_OK)
                finish()
            }
        }
    }

    /**
     * 调用设置密码接口
     */
    private fun request(request: (pwd: String) -> Unit) {
        val pwd = getEditTextString(R.id.et_pwd)
        val newPwd = getEditTextString(R.id.et_new_pwd)
        val phone = intent.getStringExtra("phone") ?: ""
        if (!checkPasswordAlike(pwd, newPwd)) return
        HttpManager.settingPas(app.user.userId, pwd, phone)
                .requestSucceed(this@SetPasswordActivity) {
                    request.invoke(pwd)
                }
    }
}
